<template>
  <div id="department">
      <!-- 面包导航 -->
    <el-breadcrumb separator="/" style="padding-left:10px;padding-bottom:10px;font-size:12px;">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>部门管理</el-breadcrumb-item>
    </el-breadcrumb>
     <!-- 用户列表卡片区 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            clearable=""
            v-model="queryMap.deptName"
            placeholder="请输入部门查询"
            @clear="search"
            class="input-with-select"
          >
            <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button
            type="success"
            icon="el-icon-circle-plus-outline"
            @click="add"
          >添加
          </el-button>
        </el-col>
        <el-col :span="2">
          <el-button
            icon="el-icon-download"
            @click="downExcel"
          >导出
          </el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <template>
        <el-table
          border
          v-loading="loading"
          stripe
          :data="departmentData"
          style="width: 100%;margin-top:20px;"
          height="460"
        >
          <el-table-column prop="id" label="ID" width="50"></el-table-column>
          <el-table-column prop="phone" label="办公电话" width="180"></el-table-column>
          <el-table-column prop="name" label="部门名" width="120"></el-table-column>
          <el-table-column prop="deptCount" label="人数" sortable="" width="80">
            <template slot-scope="scope">
              <el-tag effect="plain" v-text="scope.row.deptCount+'人'" size="mini">
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" sortable=""></el-table-column>
          <el-table-column prop="modifiedTime" label="修改时间" width="180" sortable=""></el-table-column>
          <el-table-column prop="mgrName" label="部门主任" width="140"></el-table-column>
          <el-table-column prop="address" label="地址" width="180"></el-table-column>
          <el-table-column label="操作" fixed="right" width="120">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="mini"
                icon="el-icon-edit"
                @click="edit(scope.row)"
              >编辑
              </el-button>

              <el-button
                type="text"
                size="mini"
                icon="el-icon-delete"
                @click="del(scope.row.id)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>

      <!-- 部门添加或修改弹出框 -->
      <el-dialog :title="title" :visible.sync="addOrEditDialogVisible" width="50%"
                 @close="closeDialog">
        <span>
          <el-form
            :model="form"
            :rules="Rules"
            ref="form"
            label-width="100px"
            class="demo-ruleForm">
            <el-form-item label="部门名称" prop="name">
              <el-input v-model="form.name"></el-input>
            </el-form-item>
            <el-form-item label="部门主任" prop="mgrId">
              <el-select clearable @clear="search" v-model="form.mgrId" placeholder="请选择" value="">
                <el-option
                  v-for="(item, index) in deans"
                  :key="index"
                  :label="item.nickname"
                  :value="item.id"
                  @click.native="search">
                  <span style="float: left">{{ item.nickname }}</span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="办公电话" prop="phone">
              <el-input v-model="form.phone"></el-input>
            </el-form-item>
            <el-form-item label="办公地址" prop="address">
              <el-input type="textarea" v-model="form.address"></el-input>
            </el-form-item>
          </el-form>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addOrEditDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </el-dialog>

    </el-card>
  </div>
</template>
<script>
import {addDept, deleteDept, downDeptExcel, getDeptList, updateDept} from '@/api/dept';
import { findUserList } from '@/api/users';

export default {
  name: 'department',
  components:{

  },
  data () {
      var checkPhone = (rule, value, callback) => {
        const phoneReg = /^1[34578]\d{9}$$/
        if (!value) {
          return callback(new Error('电话号码不能为空'))
        }
        setTimeout(() => {
          if (!Number.isInteger(+value)) {
            callback(new Error('请输入数字值'))
          } else {
            if (phoneReg.test(value)) {
              callback()
            } else {
              callback(new Error('电话号码格式不正确'))
            }
          }
        }, 100)
      }
      return {
        loading: true,
        addOrEditDialogVisible: false, //添加弹框是否显示
        title: '',
        departmentData: [], //表格数据
        queryMap: { deptName: '' }, //查询对象
        form: {}, //添加表单数据
        deans: [], //所有部门主任
        Rules: {
          name: [
            {
              required: true,
              message: '请输入部门名称',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 10,
              message: '长度在 3 到 10 个字符',
              trigger: 'blur'
            }
          ],
          address: [
            {
              required: true,
              message: '请输入办公地址',
              trigger: 'blur'
            },
            {
              min: 4,
              max: 12,
              message: '长度在 4 到 12 个字符',
              trigger: 'blur'
            }
          ],
          mgrId: [{
            required: true,
            message: '请选择部门主任',
            trigger: 'blur'
          }],
          phone: [
            {
              required: true,
              validator: checkPhone,
              trigger: 'blur'
            }
          ]
        } //添加验证
      }
    },
  created(){
    this.getDepartmentList()
    this.getBeanList()
    setTimeout(()=>{
      this.loading = false;
    })
  },
  methods:{
      //加载部门列表
      getDepartmentList(){
        getDeptList(this.queryMap).then(res =>{
          if(res.code === 200){
            this.departmentData = res.data.departments;
          }
        })
      },
      search(){
        this.getDepartmentList()
      },
      reFresh(){
        this.getDepartmentList()
      },
      downExcel(){
        downDeptExcel().then(res =>{
           let url = window.URL.createObjectURL(res);// 将二进制文件转化为可访问的url
            //console.log(url);
            var a = document.createElement("a");
            document.body.appendChild(a);
            a.href = url;
            a.download = '部门信息.xls';
            a.click();
            window.URL.revokeObjectURL(url);           
        })
      },
      add(){
          this.title = '添加部门'
          this.addOrEditDialogVisible = true
      },
      async edit(row){
          this.title = '修改部门'
          console.log(row);
          console.log(JSON.parse(JSON.stringify(row)));
          this.form = JSON.parse(JSON.stringify(row))
          this.addOrEditDialogVisible = true
      },
      async del(id){
          const res = await this.$confirm(
            '此操作将永久删除该用户，是否继续',
            '提示',
            {
              confirmButtonText : '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
          ).catch(()=>{
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })

          if(res === 'confirm'){
            deleteDept(id).then(resp =>{
              if(resp){
                this.$message.success('部门删除成功')
                this.getDepartmentList()
              }
            })
          }
      },
      submitForm(){
        this.$refs['form'].validate(async valid =>{
          if(valid){
            if(this.form.id === undefined){
              addDept(this.form).then(res =>{
                if(res.code === 200){
                  this.$message.success('部门添加成功')
                  this.reFresh()
                  this.addOrEditDialogVisible = false
                  setTimeout(() =>{
                    this.closeDialog()
                  },500)
                }
              })
            }else{
              this.form.createTime = undefined
              this.form.modifiedTime = undefined
              updateDept(this.form).then(res =>{
                if(res.code === 200){
                  this.$message.success('部门修改成功')
                  this.reFresh()
                  this.addOrEditDialogVisible = false
                  setTimeout( () =>{
                    this.closeDialog()
                  },500)
                }
              })
            }
          }
        })
      },
      closeDialog(){
          this.addOrEditDialogVisible = false
          this.$refs['form'].resetFields()
          this.form = {}
      },
      //查询部门主任
      getBeanList(){
        findUserList(1,100,{roleId : 140}).then(res =>{
          if(res.code === 200){
            this.deans = res.data.records
          }
        })
      }
    }
    
  }

</script>